package com.example.ktdemo.progressbar;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

/**
 * FileName: ProgressHorizontalBar
 * Author: lzt
 * Date: 2023/3/16 18:11
 */
public class ProgressVerticalBar extends View {

    /**
     * 当前进度
     */
    private ProgressBarInfo mProgress = null;
    /**
     * 宽高
     */
    private int mWidth, mHeight = 0;

    private Paint mPaint;

    public ProgressVerticalBar(Context context) {
        super(context);
        init();
    }

    public ProgressVerticalBar(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ProgressVerticalBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        initPaint();
    }

    private void initPaint() {
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setStrokeWidth(1);
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setTextAlign(Paint.Align.LEFT);
    }

    /**
     * 能否绘制
     */
    private boolean canDraw() {
        this.mWidth = getMeasuredWidth();
        this.mHeight = getMeasuredHeight();
        return this.mWidth != 0 && mHeight != 0 && View.VISIBLE == getVisibility()
                && mProgress != null && mProgress.getProgress() >= 0
                && mProgress.getProgress() <= 100;
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (!canDraw()) {
            return;
        }
        canvas.save();
        //计算progress
        mPaint.setColor(this.mProgress.getProgressColor());
        int drawHeight = (int) (mHeight * (mProgress.getProgress() / 100f));
        canvas.drawRect(0, mHeight -drawHeight, mWidth, mHeight, mPaint);
        canvas.restore();
    }

    /**
     * 设置进度条
     */
    public void setProgress(ProgressBarInfo progress) {
        if (progress == null) {
            return;
        }
        this.mProgress = progress;
        postInvalidate();
    }

}
